package com.github.butid.data.config;

import com.github.butid.data.RpcNettyServer;
import com.github.butid.data.netty.springboot.SpringBootNettyProperties;
import com.github.butid.data.netty.springboot.SpringContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Rpc服务器启动配置
 * @author wangjing.dc@qq.com
 * @since 2020/8/20
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "butnetty.boot", name = "rpcServerPort")
@EnableConfigurationProperties(SpringBootNettyProperties.class)
public class RpcServerConfigration {

    @Autowired
    private SpringBootNettyProperties properties;

    @Bean
    public RpcServerStarter prcServer(){
        return new RpcServerStarter();
    }

    @Bean
    @ConditionalOnMissingBean(SpringContext.class)
    public SpringContext springContext() {
        return new SpringContext();
    }

    private class RpcServerStarter implements InitializingBean, DisposableBean {

        RpcNettyServer server;

        @Override
        public void afterPropertiesSet() throws Exception {
            log.info("---------------------------< Starting The Rpc Server >---------------------------------");
            long start = System.currentTimeMillis();

            server = new RpcNettyServer(properties.getRpcServerPort());
            server.start();

            log.info("Rpc Server listening on :{}", properties.getRpcServerPort());
            log.info("-------------------------< Started The Rpc Server in {}s>-------------------------------", (System.currentTimeMillis() - start) / 1000);
        }

        @Override
        public void destroy() throws Exception {
            server.stop();
        }


    }

}
